package com.zhangyanqiang.traceId.filter;

import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

/**
 * @author zhangyanqiang
 * @date 2020/7/30
 **/
@Activate(group = "provider",order = -1)
public class DubboProviderTraceFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(WebTraceIdFilter.class);
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {


        Result result = null;
        try {
            String logTraceId = RpcContext.getContext().getAttachment(TraceIdUtil.logTraceId);
            if (StringUtils.isNotEmpty(logTraceId)){
                MDC.put(TraceIdUtil.logTraceId,logTraceId);
            }
            result= invoker.invoke(invocation);
        }catch (Exception e){
            logger.error("failed to get dubbo traceId:{}",e);
        }finally {
            TraceIdUtil.removeLogTraceId();
        }
        return result;


    }
}
